package pro.cherish.quartzlockdemo.controller;

import com.alibaba.druid.support.json.JSONUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pro.cherish.quartzlockdemo.da.GiveBack;
import pro.cherish.quartzlockdemo.da.InitQuartzJob;
import pro.cherish.quartzlockdemo.da.ScheduleJob;
import pro.cherish.quartzlockdemo.entity.STimetask;
import pro.cherish.quartzlockdemo.service.STimetaskService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller
@Api(tags = "时间任务接口")
@RequestMapping(value = "/admin/task")
@Slf4j
public class TimetaskController {

    @Autowired
    STimetaskService sTimetaskService;
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;


    /**
     * 加入计划
     *
     * @return
     */
    @ApiOperation("加载已有job到quartz")
    @PostMapping("addJob")
    @ResponseBody
    public GiveBack addJob(String id) {
        String code = "";
        String message = "";
        String data = null;
        STimetask sTimetask = sTimetaskService.selectByPrimaryKey(id);
        if (sTimetask == null) {
            code = "404";
            message = "未找到该任务";
            return GiveBack.make(code, message, data);
        }
        //发布即启动
		/*if(!"1".equals(sTimetask.getJobStatus())){
			code = "1";
			message = "请先发布任务";
			return GiveBack.make(code, message, data);
		}*/
        if ("1".equals(sTimetask.getPlanStatus())) {
            code = "1";
            message = "该任务已启动";
            return GiveBack.make(code, message, data);
        }
        sTimetask.setJobStatus("1");
        sTimetask.setIsConcurrent(1);
        sTimetask.setPlanStatus("1");
        ScheduleJob job = new ScheduleJob();
        job.setJobId(sTimetask.getId());
        job.setJobGroup(sTimetask.getGroupName()); // 任务组
        job.setJobName(sTimetask.getName());// 任务名称
        job.setJobStatus(sTimetask.getJobStatus()); // 任务发布状态
        job.setIsConcurrent(sTimetask.getIsConcurrent() == 1 ? "1" : "0"); // 运行状态
        // 1:run
        // 0:stop
        job.setCronExpression(sTimetask.getCron());
        job.setBeanClass(sTimetask.getBeanName());// 一个以所给名字注册的bean的实例
        job.setMethodName(sTimetask.getMethodName());
        job.setJobData(sTimetask.getJobData()); // 参数
        try {
            InitQuartzJob.addJob(job);
            sTimetaskService.updateByPrimaryKeySelective(sTimetask);
            code = "0";
            return GiveBack.make(code, message, data);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            code = "-1";
            message = "系统异常,任务启动失败";
            return GiveBack.make(code, message, data);
        }
    }


    /**
     * 强制重启
     *
     * @return
     */
    @PostMapping("powerStartJob")
    @ResponseBody
    public GiveBack powerStartJob(String id) {
        String code = "";
        String message = "";
        String data = null;
        STimetask sTimetask = sTimetaskService.selectByPrimaryKey(id);
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(sTimetask.getName(), sTimetask.getGroupName());
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e1) {
            e1.printStackTrace();
        }
        ScheduleJob job = new ScheduleJob();
        sTimetask.setJobStatus("1");
        sTimetask.setIsConcurrent(1);
        sTimetask.setPlanStatus("1");
        job.setJobId(sTimetask.getId());
        job.setJobGroup(sTimetask.getGroupName()); // 任务组
        job.setJobName(sTimetask.getName());// 任务名称
        job.setJobStatus(sTimetask.getJobStatus()); // 任务发布状态
        job.setIsConcurrent(sTimetask.getIsConcurrent() == 1 ? "1" : "0"); // 运行状态
        // 1:run
        // 0:stop
        job.setCronExpression(sTimetask.getCron());
        job.setBeanClass(sTimetask.getBeanName());// 一个以所给名字注册的bean的实例
        job.setMethodName(sTimetask.getMethodName());
        job.setJobData(sTimetask.getJobData()); // 参数
        try {
            InitQuartzJob.addJob(job);
            sTimetaskService.updateByPrimaryKeySelective(sTimetask);
            code = "0";
            return GiveBack.make(code, message, data);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            code = "-1";
            message = "系统异常,任务启动失败";
            return GiveBack.make(code, message, data);
        }
    }

    /**
     * 暂停计划
     *
     * @return
     */
    @PostMapping("stopJob")
    @ResponseBody
    public GiveBack stopJob(String id) {
        String code = "";
        String message = "";
        String data = null;

        STimetask sTimetask = sTimetaskService.selectByPrimaryKey(id);
        if (sTimetask == null) {
            code = "404";
            message = "未找到该任务";
            return GiveBack.make(code, message, data);
        }
        if (!"1".equals(sTimetask.getPlanStatus())) {
            code = "1";
            message = "请先加入计划";
            return GiveBack.make(code, message, data);
        }
        if ("0".equals(sTimetask.getPlanStatus())) {
            code = "1";
            message = "该任务已暂停";
            return GiveBack.make(code, message, data);
        }
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(sTimetask.getName(), sTimetask.getGroupName());
        try {
            scheduler.pauseJob(jobKey);
            sTimetask.setIsConcurrent(0);
            sTimetask.setPlanStatus("0");
            sTimetaskService.updateByPrimaryKeySelective(sTimetask);
            code = "0";
            return GiveBack.make(code, message, data);
        } catch (SchedulerException e1) {
            e1.printStackTrace();
            code = "-1";
            message = "暂停失败";
            return GiveBack.make(code, message, data);
        }
    }

    /**
     * 恢复计划
     *
     * @return
     */
    @PostMapping("resumeJob")
    @ResponseBody
    public GiveBack resumeJob(String id) {
        String code = "";
        String message = "";
        String data = null;

        STimetask sTimetask = sTimetaskService.selectByPrimaryKey(id);
        if (sTimetask == null) {
            code = "404";
            message = "未找到该任务";
            return GiveBack.make(code, message, data);
        }
        if (!"0".equals(sTimetask.getPlanStatus()) && !"1".equals(sTimetask.getJobStatus())) {
            code = "1";
            message = "请先加入计划";
            return GiveBack.make(code, message, data);
        }
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(sTimetask.getName(), sTimetask.getGroupName());
        try {
            scheduler.resumeJob(jobKey);
            sTimetask.setIsConcurrent(1);
            sTimetask.setPlanStatus("1");
            sTimetaskService.updateByPrimaryKeySelective(sTimetask);
            code = "0";
            return GiveBack.make(code, message, data);
        } catch (SchedulerException e1) {
            e1.printStackTrace();
            code = "-1";
            message = "恢复失败";
            return GiveBack.make(code, message, data);
        }
    }

    /**
     * 移除计划
     *
     * @return
     */
    @PostMapping("removeJob")
    @ResponseBody
    public GiveBack removeJob(String id) {
        String code = "";
        String message = "";
        String data = null;

        STimetask sTimetask = sTimetaskService.selectByPrimaryKey(id);
        if (sTimetask == null) {
            code = "404";
            message = "未找到该任务";
            return GiveBack.make(code, message, data);
        }
        if ((!"0".equals(sTimetask.getPlanStatus())) && (!"1".equals(sTimetask.getPlanStatus()))) {
            code = "1";
            message = "该任务已移除";
            return GiveBack.make(code, message, data);
        }
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(sTimetask.getName(), sTimetask.getGroupName());
        try {
            scheduler.deleteJob(jobKey);
            sTimetask.setJobStatus("0");
            sTimetask.setIsConcurrent(0);
            sTimetask.setPlanStatus("-1");
            sTimetaskService.updateByPrimaryKeySelective(sTimetask);
            code = "0";
            return GiveBack.make(code, message, data);
        } catch (SchedulerException e1) {
            e1.printStackTrace();
            code = "-1";
            message = "移除失败";
            return GiveBack.make(code, message, data);
        }
    }


    @PostMapping("getJob")
    @ResponseBody
    public GiveBack getJob() throws SchedulerException {
        String code = "";
        String message = "";
        String data = null;

        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
            for (JobKey jobKey : jobKeys) {
                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                for (Trigger trigger : triggers) {
                    ScheduleJob job = new ScheduleJob();
                    job.setJobId(trigger.getDescription());//description 放的是job的id
                    job.setJobName(jobKey.getName());
                    job.setJobGroup(jobKey.getGroup());
                    job.setDescription("触发器:" + trigger.getKey());
                    Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                    job.setJobStatus(triggerState.name());
                    if (trigger instanceof CronTrigger) {
                        CronTrigger cronTrigger = (CronTrigger) trigger;
                        String cronExpression = cronTrigger.getCronExpression();
                        job.setCronExpression(cronExpression);
                    }
                    jobList.add(job);
                }
            }

            if (jobList.size() == 0) {
                data = "";
            } else {
                data = JSONUtils.toJSONString(jobList);
            }
            code = "0";
            return GiveBack.make(code, message, data);
        } catch (Exception e) {
            e.printStackTrace();
            code = "-1";
            message = "系统异常";
            return GiveBack.make(code, message, data);
        }
    }


}